#/bin/bash

# protoc 
PB_SOURCE_DIR=$GOPATH/bgs/grpc/pb
PB_DIR=./pb
PB_GEN_DIR=./src/grpc-client
PB_MODULE_DIRS=(shared util service)

NODE_PROTOC_JS_OUT_ROOT=import_style=commonjs,binary
NODE_PROTOC_PLUG=protoc-gen-grpc=`which grpc_tools_node_protoc_plugin`
TS_PROTOC_PLUG=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts

for MOD_NAME in ${PB_MODULE_DIRS[@]};
do
    MOD_SOURCE=$PB_SOURCE_DIR/$MOD_NAME
    MOD_PATH=$PB_DIR/$MOD_NAME
    MOD_OUTPUT_PATH=$PB_GEN_DIR/$MOD_NAME
    echo $MOD_PATH
    echo $MOD_OUTPUT_PATH
    mkdir -p $MOD_PATH
    for FILE in `ls $MOD_SOURCE | grep ".proto$"`
    do
      if [ ! -f "$FILE" ]; then
        # 存在文件
        echo $FILE
        FILE_SOURCE_PATH=$MOD_SOURCE/$FILE
        FILE_PATH=$MOD_PATH/$FILE
        
        # echo $FILE_SOURCE_PATH
        # echo $FILE_PATH
        #1、通过软连接使项目能够访问指定的grpc proto file
        if [ -L "$FILE_PATH" ]; then
          echo "exist symbolic: $FILE_PATH -> $FILE_SOURCE_PATH"
        else
          echo "create symbolic: $FILE_PATH -> $FILE_SOURCE_PATH"
          ln -s $FILE_SOURCE_PATH $FILE_PATH
        fi
        
        # FILE_NAME=$(echo $FILE | sed 's/\.[^.]*$//')
        # FILE_OUTPUT_PATH=$MOD_OUTPUT_PATH/$FILE_NAME
        # mkdir -p $FILE_OUTPUT_PATH
        # SHARD_PROTO_PATH=$PB_DIR/shared      
        
        #2、生成grpc gen js
        grpc_tools_node_protoc \
        -I $PB_DIR \
        --js_out=$NODE_PROTOC_JS_OUT_ROOT:$PB_GEN_DIR \
        --grpc_out=$PB_GEN_DIR \
        --plugin=$NODE_PROTOC_PLUG \
        $MOD_NAME/$FILE

        #3、生成 d.ts codes
        protoc \
        -I $PB_DIR \
        --plugin=$TS_PROTOC_PLUG \
        --ts_out=$PB_GEN_DIR \
        $MOD_NAME/$FILE
       
      fi
    done;
done;

# PB_PROXY_DIR=./pb/proxy
# PB_PROXY_GEN_DIR=./src/grpc-client/proxy

## others service of bgs
# 生成grpc gen js
grpc_tools_node_protoc \
-I $PB_DIR \
--js_out=$NODE_PROTOC_JS_OUT_ROOT:$PB_GEN_DIR \
--grpc_out=$PB_GEN_DIR \
--plugin=$NODE_PROTOC_PLUG \
others/thirdparty.proto

# 生成 d.ts codes
protoc \
-I $PB_DIR \
--plugin=$TS_PROTOC_PLUG \
--ts_out=$PB_GEN_DIR \
others/thirdparty.proto

# proxy for proxy grpc service endpoint

# 生成grpc gen js
grpc_tools_node_protoc \
-I $PB_DIR \
--js_out=$NODE_PROTOC_JS_OUT_ROOT:$PB_GEN_DIR \
--grpc_out=$PB_GEN_DIR \
--plugin=$NODE_PROTOC_PLUG \
proxy/account.proto proxy/bilinadmin.proto proxy/gsms.proto proxy/inventory.proto proxy/wxpay.proto

# 生成 d.ts codes
protoc \
-I $PB_DIR \
--plugin=$TS_PROTOC_PLUG \
--ts_out=$PB_GEN_DIR \
proxy/account.proto proxy/bilinadmin.proto proxy/gsms.proto proxy/inventory.proto proxy/wxpay.proto

# protos of thirdparty

# # 生成grpc gen js
# grpc_tools_node_protoc \
# -I $PB_DIR \
# --js_out=$NODE_PROTOC_JS_OUT_ROOT:$PB_GEN_DIR \
# --grpc_out=$PB_GEN_DIR \
# --plugin=$NODE_PROTOC_PLUG \
# thirdparty/google_timestamp.proto

# # 生成 d.ts codes
# protoc \
# -I $PB_DIR \
# --plugin=$TS_PROTOC_PLUG \
# --ts_out=$PB_GEN_DIR \
# thirdparty/google_timestamp.proto